// 📦 引入工具库
const _ = require("lodash");
const path = require("path");
const fs = require("fs");

// 📦 ESM 支持模块加载
const esm = require("esm");
const requireModule = esm(module);

// 📦 项目依赖模块
const { readAllValues } = requireModule(
  "../../../awakened-potential/helpers/readAllValues.js"
);
const checkAccuracy = requireModule("../../utils/checkAccuracy.js");

// ✅ 读取历史开奖数据（模拟全部）
const allValues = readAllValues("m");

// ✅ 号码池（01 ~ 49）
const allNumbers = Array.from({ length: 49 }, (_, i) =>
  (i + 1).toString().padStart(2, "0")
);

// ✅ 是否使用窗口
const useWindow = true;
// ✅ 窗口大小
const windowSize = 5;

// ✅ 存储预测结果
const predictResults = [];
let correct = 0;
let maxWrongStreak = 0;
let currentWrongStreak = 0;

/**
 * 上期邻号策略（邻接数字优先）
 * - 获取上期开奖号码
 * - 生成其邻号（±1），如果合法（01~49）则加入权重集合
 * - 再统计这些邻号在窗口期内的活跃次数
 * - 评分 = 是否是邻号 + 出现次数
 */
function select32ByNeighborStrategy(temp, lastNumber) {
  const lastNum = parseInt(lastNumber, 10);
  const neighbors = [];

  if (lastNum > 1) neighbors.push((lastNum - 1).toString().padStart(2, "0"));
  if (lastNum < 49) neighbors.push((lastNum + 1).toString().padStart(2, "0"));

  // 在 temp 中统计频率
  const freqMap = {};
  temp.forEach((item) => {
    const num = item.number;
    freqMap[num] = (freqMap[num] || 0) + 1;
  });

  // 计算得分（邻号得 +5 分，频率 +1 分）
  const scored = allNumbers.map((num) => {
    const isNeighbor = neighbors.includes(num);
    const freq = freqMap[num] || 0;
    return {
      number: num,
      score: (isNeighbor ? 5 : 0) + freq,
    };
  });

  return _.orderBy(scored, ["score", "number"], ["desc", "asc"])
    .slice(0, 32)
    .map((x) => x.number);
}

// ✅ 主预测循环
allValues.forEach((item, index) => {
  const temp = useWindow
    ? allValues.slice(Math.max(0, index - windowSize), index)
    : allValues.slice(0, index);

  if (temp.length === 0) return;

  const lastNumber = allValues[index - 1]?.number;
  if (!lastNumber) return;

  const selectedNumbers = select32ByNeighborStrategy(temp, lastNumber);
  if (selectedNumbers.length !== 32) {
    throw new Error(`❌ 选出的号码数量不足32个`);
  }

  const isHit = checkAccuracy(selectedNumbers, item.number);
  if (isHit) {
    correct++;
    currentWrongStreak = 0;
  } else {
    currentWrongStreak++;
    maxWrongStreak = Math.max(maxWrongStreak, currentWrongStreak);
  }

  predictResults.push(selectedNumbers);
});

// ✅ 输出结果统计
const total = predictResults.length;
const accuracy = total > 0 ? ((correct / total) * 100).toFixed(2) : 0;

console.log(`✅ 上期邻号策略`);
console.log(`预测总数: ${total}`);
console.log(`命中次数: ${correct}`);
console.log(`准确率: ${accuracy}%`);
console.log(`最大连续错误次数: ${maxWrongStreak}`);
